#!/usr/bin/env python3
"""
调试API响应
Debug API Response
"""

import sys
import os
import requests
from pprint import pprint

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_api_response():
    """测试API响应"""
    print("🔍 调试铺先生API响应")
    print("=" * 50)
    
    # 测试URL
    urls = [
        "https://sz.puxiansheng.com/find_list-hy-1.html",  # 餐饮
        "https://sz.puxiansheng.com/find_list-hy-4.html",  # 娱乐
    ]
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    
    for url in urls:
        print(f"\n🌐 测试URL: {url}")
        print("-" * 50)
        
        try:
            response = requests.get(url, headers=headers, timeout=30)
            print(f"状态码: {response.status_code}")
            print(f"Content-Type: {response.headers.get('content-type', 'unknown')}")
            print(f"响应长度: {len(response.text)} 字符")
            
            # 检查是否是JSON
            try:
                json_data = response.json()
                print("✅ 响应是JSON格式")
                print("JSON结构:")
                pprint(json_data, depth=2)
            except:
                print("❌ 响应不是JSON格式")
                print("HTML内容前500字符:")
                print(response.text[:500])
                print("...")
                
                # 检查是否包含特定的HTML元素
                if '<li' in response.text:
                    print("✅ 发现<li>元素")
                if 'class="title"' in response.text:
                    print("✅ 发现title类")
                if 'class="item2"' in response.text:
                    print("✅ 发现item2类")
                    
        except Exception as e:
            print(f"❌ 请求失败: {e}")
    
    print("\n" + "=" * 50)

def test_with_ajax_headers():
    """测试使用AJAX请求头"""
    print("\n🔄 测试AJAX请求")
    print("=" * 50)
    
    url = "https://sz.puxiansheng.com/find_list-hy-1.html"
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'X-Requested-With': 'XMLHttpRequest',
        'Referer': 'https://sz.puxiansheng.com/'
    }
    
    try:
        response = requests.get(url, headers=headers, timeout=30)
        print(f"状态码: {response.status_code}")
        print(f"Content-Type: {response.headers.get('content-type', 'unknown')}")
        print(f"响应长度: {len(response.text)} 字符")
        
        try:
            json_data = response.json()
            print("✅ AJAX请求返回JSON格式")
            print("JSON结构:")
            pprint(json_data, depth=2)
        except:
            print("❌ AJAX请求也不是JSON格式")
            print("响应内容前200字符:")
            print(response.text[:200])
            
    except Exception as e:
        print(f"❌ AJAX请求失败: {e}")

def test_with_page_param():
    """测试带页码参数的请求"""
    print("\n📄 测试带页码参数的请求")
    print("=" * 50)
    
    urls = [
        "https://sz.puxiansheng.com/find_list-hy-1.html?page=1",
        "https://sz.puxiansheng.com/find_list-hy-1.html?p=1",
    ]
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    
    for url in urls:
        print(f"\n🌐 测试URL: {url}")
        try:
            response = requests.get(url, headers=headers, timeout=30)
            print(f"状态码: {response.status_code}")
            print(f"响应长度: {len(response.text)} 字符")
            
            try:
                json_data = response.json()
                print("✅ 返回JSON格式")
                if 'total_page' in json_data:
                    print(f"总页数: {json_data['total_page']}")
                if 'page_num' in json_data:
                    print(f"当前页: {json_data['page_num']}")
            except:
                print("❌ 不是JSON格式")
                
        except Exception as e:
            print(f"❌ 请求失败: {e}")

def main():
    """主函数"""
    test_api_response()
    test_with_ajax_headers()
    test_with_page_param()
    
    print("\n🎯 调试完成!")
    print("如果所有请求都返回HTML而不是JSON，可能需要:")
    print("1. 检查网站是否更改了API接口")
    print("2. 尝试不同的请求头或参数")
    print("3. 检查是否需要登录或验证")
    print("4. 分析网站的实际AJAX请求")

if __name__ == "__main__":
    main()
